package com.powergisol.gis.controller;

import cn.hutool.core.io.resource.ResourceUtil;
import com.google.code.kaptcha.Producer;
import com.powergisol.gis.core.CaptchaResult;
import com.powergisol.gis.core.CaptchaVo;
import com.powergisol.gis.core.PuzzleCaptcha;
import com.powergisol.gis.util.CaptchaUtil;
import com.powergisol.gis.util.RASUtils;
import com.powergisol.gis.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.security.KeyPair;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping(value = "code")
public class LoginController {
    @Autowired
    private Producer producer;

    @Resource
    private CacheManager cacheManager;

    @Autowired
    private CaptchaUtil captchaUtil;

    @GetMapping(value = "/getcaptcha")
    public CaptchaVo captcha() {
        PuzzleCaptcha puzzleCaptcha = new PuzzleCaptcha(ResourceUtil.getStream("images/captcha/default.jpg"));
        puzzleCaptcha.setImageQuality(Image.SCALE_AREA_AVERAGING);
        puzzleCaptcha.run();
        return captchaUtil.captcha(puzzleCaptcha);
    }

    @PostMapping(value = "/verify")
    public CaptchaResult verify(String x, String width) {
        Map<String, Object> map = new HashMap<>();
        map.put("x",x);
        map.put("width",width);
        return captchaUtil.verify(map);
    }

    @GetMapping("/getCaptcha")
    public void getCode(HttpServletResponse response, HttpServletRequest request) throws Exception {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //生成文字验证码
        String text = producer.createText();
        //保存验证码信息
        String randomStr = request.getParameter("randomStr");
        Cache cache = cacheManager.getCache("cache-data");
        cache.put("imageCode" + randomStr,text);
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
    }
    /**
     * 验证验证码
     *
     * @param code
     */
    @GetMapping("checkCaptcha")
    public Result checkCaptcha(String code, String randomStr) {
        try {
            String key = "imageCode" + randomStr;
            Cache cache = cacheManager.getCache("cache-data");
            if (null == cache.get(key)) {
                return new Result().failure(-1,"请重新获取验证码");
            }
            String text = cache.get(key,String.class);
            if (null == text) {
                return new Result().failure(-1,"请重新获取验证码");
            }
            if (!text.equalsIgnoreCase(code)) {
                cache.evict(key);
                return new Result().failure(-1,"验证码错误");
            }
            cache.evict(key);
        } catch (Exception e) {
            return new Result().failure(-1, e.getMessage());
        }
        return new Result().success();
    }
    @GetMapping("getkey")
    public Result getKey(String randomStr) {
        HashMap<Object, Object> hashMap = new HashMap<>();
        RSAPublicKey rsapPublicKey = null;
        RSAPrivateKey rsaPrivateKey = null;
        try {
            KeyPair publicKey = RASUtils.generateKeyPair();
            rsapPublicKey = (RSAPublicKey) publicKey.getPublic();
            rsaPrivateKey = (RSAPrivateKey) publicKey.getPrivate();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Cache cache = cacheManager.getCache("cache-data");
        cache.put("privateKey" + randomStr,rsaPrivateKey);
        hashMap.put("publicKey", rsapPublicKey.getModulus().toString(16));
        return new Result().success(hashMap);
    }
}
